<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/1/23
 * Time: 21:33
 */

namespace app\admin\controller;

use app\home\model\CreditRecord;
use app\home\model\Member;
use think\Db;
use think\Log;
use think\Loader;

class Task extends Base{

    //任务列表
    public function index(){
        if(request()->isAjax()){
            $ids = params_array('ids');
            if(!check_array($ids)){
                message('请选择要删除的任务','','error');
            }
            $status = \app\admin\model\Task::deleteByIds($ids);
            if(!$status){
                message('删除失败','','error');
            }
            message('删除成功','reload','success');
        }

        $params = request()->get();
        $where = [];
        if(check_array($params)){
            if(!empty($params['keyword'])){
            	if(is_numeric($params['keyword'])){
            		$where['uid']=$params['keyword'];
            	}else{
	                $where['id|title'] = ['like', "%{$params['keyword']}%"];
            	}
                
            }
            if(!empty($params['is_display'])){
                $where['is_display'] = ['in',$params['is_display']];
            }
            if(!empty($params['is_stop'])){
                $where['is_stop'] = ['in',$params['is_stop']];
            }
            if(!empty($params['out_stock_flag'])){
                $where['out_stock_flag'] = ['in',$params['out_stock_flag']];
            }
            if(!empty($params['appName'])){
                $where['appName'] = $params['appName'];
            }
            if(!empty($params['category_id'])){
                $where['category_id'] = ['in',$params['category_id']];
            }
            

            
        }   
        
             $order_str='';
             if(!empty($params['rank'])){
             	$order_str="unit_price DESC";
            }else{
             	$order_str="update_time DESC";
            	
            }
		
        $total = \app\admin\model\Task::getCount($where);
        $list = \app\admin\model\Task::getPagination($where, 15, $total, $order_str);
		
        $categorys = [];
        $categories = \app\admin\model\TaskCategory::getList();
        foreach ($categories as $key => $value) {
            $categorys[$value['id']] = $value['title'];
        }

        $GLOBALS['categorys'] = $categorys;

        $itemsCallback = function ($item, $key) {
            $item['category_type'] = "";

            if ($item['end_time'] < TIMESTAMP) {
                $item['category_type'] = "past";
            }  else if ($item['is_complete'] == 1) {
                $item['category_type'] = "pass";
            }   else if ($item['is_display'] == 0) {
                $item['category_type'] = "wait";
            } else if ($item['start_time'] < TIMESTAMP && $item['end_time'] > TIMESTAMP) {
                $item['category_type'] = "ing";
            }

            $item['start_time'] = date('Y-m-d H:i', $item['start_time']);
            $item['end_time'] = date('Y-m-d H:i', $item['end_time']);
            $item['nickname'] = db('member')->where('uid',$item['uid'])->value('nickname');
            $item['complete_time'] = date('Y-m-d H:i', $item['complete_time']);
            $item['category'] = isset($GLOBALS['categorys'][$item['category_id']]) ? $GLOBALS['categorys'][$item['category_id']] : '';
            return $item;
        };

        $list->each($itemsCallback);
	
        $pager = $list->render();
        return $this->fetch(__FUNCTION__,[
            'list' => $list,
            'pager' => $pager,
            'total' => $total
        ]);
    }

    public function post(){
        $id = params('id');
        $item = [];
        if(check_id($id)){
            $categorys = [];
            $categories = \app\admin\model\TaskCategory::getList();
            foreach ($categories as $key => $value) {
                $categorys[$value['id']] = $value['title'];
            }

            $item = \app\admin\model\Task::getInfoById($id);
            if(!empty($item['thumbs'])){
                $item['thumbs'] = unserialize($item['thumbs']);
            }

            $item['fee_money'] = $item['give_credit2'] * $item['fee'];

            $operate_steps = \app\home\model\Task::getOperateStepsById($id);

            $member = \app\admin\model\Member::getInfoById($item['uid']);
            $item['username'] = $member['username'];

            $item['category_type'] = "";

            if ($item['end_time'] < TIMESTAMP) {
                $item['category_type'] = "past";
            } else if ($item['is_complete'] == 1) {
                $item['category_type'] = "complete";
            } else if ($item['is_display'] == 0) {
                $item['category_type'] = "wait";
            } else if ($item['is_display'] == -1) {
                $item['category_type'] = "nopass";
            } else if ($item['start_time'] < TIMESTAMP && $item['end_time'] > TIMESTAMP) {
                $item['category_type'] = "ing";
            }

            $item['start_time'] = date('Y-m-d H:i:s', $item['start_time']);
            $item['end_time'] = date('Y-m-d H:i:s', $item['end_time']);
            $item['complete_time'] = date('Y-m-d H:i:s', $item['complete_time']);
            $item['category'] = isset($categorys[$item['category_id']]) ? $categorys[$item['category_id']] : '';

        }
        $categorylist=array(array());
        foreach ($categories as $key => $value){
            $categorylist[$key]['id']=$value['id'];
            $categorylist[$key]['title']=$value['title'];
        }
        return $this->fetch(__FUNCTION__,[
            'item' => $item,
            'categorylist'=>$categorylist,
            'operate_steps' => $operate_steps,
            'origin' => $item->getData()
        ]);
    }
    //直接审核通过
    public function pass(){
    	$res = db('task')->where('id',input('id'))->setField('is_display',1);
    	if($res){
    		message("成功",'','success');
    	}else{
    		message("失败",'','error');
    	}
    }
    //直接审核不通过
    public function nopass(){
    	$data['audit_remarks'] = input('reson');
    	$data['is_display'] = -1;
    	$res = db('task')->where('id',input('id'))->update($data);
    	if($res){
    		message("成功",'','success');
    	}else{
    		message("失败",'','error');
    	}
    }

    public function save(){
        $id = params('id');
        $item = [];
        if(check_id($id)){
            $item = \app\admin\model\Task::getInfoById($id);
        }
        if (empty($item) || is_null($item)) {
            message("审核失败",'','error');
        }

        $origin = $item->getData();

        //2019-05-18修改，保证可以重复修改
//        if ($origin['admin_id'] > 0) {
//            message("审核失败",'','error');
//        }

        $params = array_trim(request()->post());

        Db::startTrans();

        $update = [];
        $update['title'] = $params['title'];
        $update['appName'] = $params['appName'];
        $update['task_time'] = $params['task_time'];
        $update['task_checkout_time'] = $params['task_checkout_time'];
        $update['category_id']=$params['category_id'];
        $update['is_display'] = intval($params['is_display']);
        $update['audit_remarks'] = $params['audit_remarks'];
        $update['admin_id'] = $this->administrator['id'];
        $update['update_time'] = TIMESTAMP;
        $status = \app\admin\model\Task::updateInfoById($id, $update);
        if(!$status){
            Db::rollback();
            message("审核失败",'','error');
        }

      

        Db::commit();

        message("审核成功",'reload','success');
    }
    public function addtask(){
    
        if(request()->isAjax()){
            $data['title']        = input('title');          //标题
            $data['category_id']  = 12;                      //分类id
            $data['start_time']   = strtotime(input('start_time'));     //开始时间
            $data['end_time']     = strtotime(input('end_time'));       //结束时间
            $data['task_time']    = 1;                       //任务时间，之前数据都是1
            $data['unit_price']   = input('unit_price');     //多少元
            $data['give_credit1'] = input('give_credit1');   //多少积分
            $data['about_url']    = input('about_url');      //url
            $data['rate']         = 1;                       //仅限一次
            $data['ticket_num']   = input('ticket_num');                       //任务份数
            $res = db('task')->insert($data);
            if($res){
                message("发布成功",'reload','success');
            }else{
                message("发布失败,联系技术",'reload','error');
            }
        }
        return $this->fetch(__FUNCTION__,[
        ]);
    }
    //暂停任务
    public function stop(){
    	$res = db("task")->where('id',input('id'))->update(['is_stop'=>1]);
    	if($res){
    		message("暂停任务成功",'','success');
    	}else{
    		message("暂停任务失败",'','error');
    	}
    }
    //开启任务
    public function kaiqi(){
    	$res = db("task")->where('id',input('id'))->update(['is_stop'=>0]);
    	if($res){
    		message("开启任务成功",'','success');
    	}else{
    		message("开启任务失败",'','error');
    	}
    }
    
    //下架
    public function xiajia(){
        $tasks = db('task')->where('id',input('id'))->find();
      	$taskjoin = db('task_join')->where(['task_id'=>$tasks['id']])->select();
      	foreach($taskjoin as $value){
         	if($value['status']==2 && $value['delflag'] == 1){
              message('还有任务未审核,无法下架','','error');
            }
          if($value['status']==1 && $value['delflag'] == 1){
              message('还有用户正在接单,无法下架','','error');
            }
          if($value['status']==4 && $value['delflag'] == 1){
              message('锁定名额中,需等24小时才可下架','','error');
            }
            if($value['is_shensu']==1){
              message('有用户发起申诉，结束后方可下架','','error');
            }
        }
        
        
        $taskService = \think\Loader::model("Task", 'service');
        $taskService->outStockTask($tasks);
        
       
        Db::startTrans();
        
		//退还红包金额
		$task_id=input('id');
		$uid=$tasks['uid'];
	
		$redpackage=\db('redpackage')->where(['task_id'=>$task_id,'is_over'=>0])->find();
		if($redpackage){
			$has_send_money=\db('redpackage_record')->where(['task_id'=>$task_id,'uid'=>['neq',0]])->sum('money');
			$has_send_number=\db('redpackage_record')->where(['task_id'=>$task_id,'uid'=>['neq',0]])->count();

			if($has_send_money <$redpackage['money']){
				//剩余金额
				$left_money=$redpackage['money']-$has_send_money;
		
				$member=db('member')->where('uid',$uid)->find();
				$credit2 = $member['credit2']+$left_money;
					    
					       // $res1 = \db('member')->where(['uid'=>$uid])->data(['credit2'=>$credit2])->update();
					          $res1 = Member::updateCreditById($uid, 0, $left_money);
					            if(!$res1){
						            Db::rollback();
						            message('操作失败:-3','','error');
						        }
		
					        $creditdata = array(
					            'uid'=>$uid,
					            'type'=>'credit2',
					            'num'=>'+'.$left_money,
					            'title'=>'下架任务返还红包余额',
					            'remark'=>'下架任务'.$task_id.'返还红包余额'.$left_money,
					            'create_time'=>time(),
					            'balance'=>$credit2,    //追加后的余额
					        );
					        $res3 = \db('credit_record')->data($creditdata)->insert();
					        if(!$res3){
					            Db::rollback();
					            message('下架失败:-5','','error');
					        }
					        
					        //标记
							\db('redpackage')->where(['task_id'=>$task_id])->setField('is_over',1);
							
							\db('redpackage_record')->where(['task_id'=>$task_id,'uid'=>0])->setField('is_back',1);
					

			}
			
		}
        
          Db::commit();
        
        back_seepackage($task_id,$uid);
        
        message('下架成功','','success');
    }
    //冻结
    public function dongjie(){
        $res = db("task")->where('id',input('id'))->update(['is_stop'=>1,'is_dj'=>0,'dj_reason'=>input('reason')]);
    	if($res){
    		message("冻结任务成功",'','success');
    	}else{
    		message("冻结任务失败",'','error');
    	}
    }
}



